﻿using System;
using System.IO;
using System.Net;

namespace Codemonk.Updater.Client.Common
{
    internal class HttpUpdateClient : IUpdateClient
    {
        public string RequestAddress { get; set; }

        public void SendUpdateInstruction(string file, string appid, Action<Exception> error, Action<System.IO.MemoryStream> back)
        {
            if (back == null) return;
            try
            {
                HttpWebRequest r = HttpWebRequest.Create(string.Concat(RequestAddress, "?file=", file, "&appid=", appid)) as HttpWebRequest;
                r.BeginGetResponse(state =>
                {
                    HttpWebRequest request = state.AsyncState as HttpWebRequest;
                    try
                    {
                        HttpWebResponse response = request.EndGetResponse(state) as HttpWebResponse;
                        using (Stream r_stream = response.GetResponseStream())
                        {
                            back(StreamHelper.Transfer(r_stream));
                        }
                    }
                    catch (Exception ex)
                    {
                        if (error != null) error(ex);
                    }
                }, r);
            }
            catch (Exception ex)
            {
                if (error != null) error(ex);
            }
        }
    }
}
